//
//  RecommendViewController.m
//  Molian
//
//  Created by 胡津 on 15/3/16.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

// 每次拉取的用户数目
#define USER_NUM_PER_TIME 50

#import "RecommendViewController.h"
#import "ArticleCell.h"

#import "CommentViewController.h"//评论

#import "ArticleViewController.h"

#import "UIScrollView+DXRefresh.h"//上拉
#import "SRRefreshView.h" //下拉刷新

@interface RecommendViewController ()<SRRefreshDelegate>

// 文章列表
@property (nonatomic, strong)NSMutableArray *articles;
@property (nonatomic, strong)NSMutableArray *jrtj;
@property (nonatomic, strong)NSMutableArray *wrtj;

// 当前分页
@property NSUInteger currentPage;

//下拉刷新
@property (strong, nonatomic) SRRefreshView *slimeView;

@end

@implementation RecommendViewController

#pragma mark - lifecycle

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = @"日报";
    
    // Do any additional setup after loading the view.
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    if(self.special){
        UIBarButtonItem *leftItem  = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(leftItem)];
        self.navigationItem.leftBarButtonItem = leftItem;
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, DeviceWidth, DeviceHeight - kNavigationBarHeight)style:UITableViewStyleGrouped];
    }else{
       self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, DeviceWidth, DeviceHeight - kNavigationBarHeight-50)style:UITableViewStyleGrouped];
    }
    
    self.tableView.backgroundColor = RGBA(244, 244, 244, 1);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = NO;
    self.tableView.separatorColor = RGBA(1, 1, 1, 0);//分隔条颜色
//    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 50, 0);//偏移量
//    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 50, 0);//滚动条偏移量
   // self.tableView.tableHeaderView = [[UIView alloc] init];
    self.tableView.tableFooterView = [[UIView alloc] init];//不显示空的cell
    [self.view addSubview:self.tableView];
    
    _slimeView = [[SRRefreshView alloc] init];
    _slimeView.delegate = self;
    _slimeView.upInset = 0;
    _slimeView.slimeMissWhenGoingBack = YES;
    _slimeView.slime.bodyColor = APPCOLOR(1);
    _slimeView.slime.skinColor = [UIColor whiteColor];
    _slimeView.slime.lineWith = 1;
    _slimeView.slime.shadowBlur = 0;
    _slimeView.slime.shadowColor = [UIColor redColor];
    [self.tableView addSubview:self.slimeView];
    
    //下拉
    [self.tableView addFooterWithTarget:self action:@selector(loadArticleData)];
    
    //用来加载好友关系
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tableViewReloadData) name:@"OnlineTableViewReloadData" object:nil];
    // 初始化专属恋人列表
    self.articles = [NSMutableArray array];
    self.jrtj = [NSMutableArray array];
    self.wrtj = [NSMutableArray array];


    
    [self loadArticleData];
    
  

}
-(void)leftItem
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)tableViewReloadData
{
    [self.tableView reloadData];
}

- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    self.currentPage = 0;
    [self loadArticleData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];//状态栏颜色
    
    
    if ([ShareData shareData].isRecommend) {
        // 刷新列表显示
        [self.tableView reloadData];
        [ShareData shareData].isRecommend = NO;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
    // Dispose of any resources that can be recreated.
}


#pragma mark - init content
-(void)loadArticleData{
    [AVAnalytics event:@"梦想恋人页面刷新"]; // 通知服务器一个like点击事件。

    // 获取推荐的独立文章
    AVQuery *articleQuery = [MLArticle query];
    [articleQuery whereKey:@"status" equalTo:[NSNumber numberWithInt:MLArticleStatus_PUBLISHED]];
    //特殊字段
    //特殊字段
    if ([Utils cheackConfigurationScreen]) {
        [articleQuery whereKey:@"checkapp" equalTo:[NSNumber numberWithInteger:1]];
    }else{
        
    }
   
   // [articleQuery includeKey:@"author"];
   [articleQuery whereKey:@"type" equalTo:[NSNumber numberWithInt:MLArticleType_INDEPENDENT]];
    [articleQuery orderByDescending:@"publishTime"];
    // 控制分页获取
    articleQuery.limit = USER_NUM_PER_TIME;
    articleQuery.skip = self.currentPage * USER_NUM_PER_TIME;
    articleQuery.cachePolicy = kAVCachePolicyNetworkElseCache;
    articleQuery.maxCacheAge = 7200;
    [articleQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            if (self.currentPage == 0) {
                [self.articles removeAllObjects];
                [self.wrtj removeAllObjects];
                [self.jrtj removeAllObjects];
            }

            self.currentPage++;
            for (int i = 0; i<objects.count; i++) {
                MLArticle *article = (MLArticle *)objects[i];
                NSString *str = [NSString stringWithFormat:@"%ld",(long)article.likeCount];
                [[ShareData shareData].likeArticlesDic setObject:str  forKey:article.objectId];
                
                NSDate * d = article.publishTime;
                NSTimeInterval late = [d timeIntervalSince1970]*1;
                NSString * timeString = nil;
                NSDate * dat = [NSDate dateWithTimeIntervalSinceNow:0];
                NSTimeInterval now = [dat timeIntervalSince1970]*1;
                NSTimeInterval cha = now - late;
                timeString = [NSString stringWithFormat:@"%f", cha/3600];
                timeString = [timeString substringToIndex:timeString.length-7];
                int num = [timeString intValue];
                if (num <= 48) {
                    [self.jrtj addObject:article];
                }else{
                    [self.wrtj addObject:article];
                }
            }
            if (objects.count != 0) {
                [self.articles addObjectsFromArray:self.jrtj.count == 0 ? @[self.wrtj]:@[self.jrtj,self.wrtj]];
            }
            
            
            [self.tableView reloadData];
        }else{
            // 加载出错, 提示
            [HUD Prompt:@"网络异常" ];
        }
        [_slimeView endRefresh];
        [self.tableView footerEndRefreshing];
    }];
}


#pragma mark - table delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // TODO 分页加载文章
    static NSString *cellIdentifier = @"ArticleCell" ;
    ArticleCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if  (cell == nil) {
        cell = [[ArticleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.tabbar = self.tabBarController;
    }
    
    // 如果文章列表为空则返回空cell
    if (self.articles.count == 0) {
        return cell;
    }
    
    MLArticle *article = self.articles[indexPath.section][indexPath.row];
    cell.article = article;
    cell.parentViewController = self;
   // cell.likeArticles = shareData.likeArticles;
    // 异步加载图片
    
    
    [cell.titleImage sd_setImageWithURL:[NSURL URLWithString:article.title_img.url]
                    placeholderImage:[UIImage imageNamed:@"common_image_loading"]];
    cell.titleLabel.text = article.title;
    cell.likeBtn.Title.text = [NSString stringWithFormat:@"%ld",(long)article.readCount];
    [cell.likeBtn layoutSubviews];
    if ([Utils inspectArticleReadObjectID:article.objectId]) {
        cell.nImageView.hidden = YES;
    }else{
         cell.nImageView.hidden = NO;
    }
    cell.likeBtn.status = NO;
    [cell.likeBtn Like:NO Alpha:0.6];
//    // 设置文章的喜欢的状态
//    BOOL isLiked = NO;
//    
//    if ([Utils isLoveArticleObjectId:article.objectId]) {
//        isLiked = YES;
//    }
//    if (!isLiked) {
//        cell.likeBtn.status = NO;
//        [cell.likeBtn Like:NO Alpha:0.6];
//    } else {
//        cell.likeBtn.status = YES;
//        [cell.likeBtn Like:YES Alpha:0.6];
//    }
    cell.backgroundColor = [UIColor whiteColor];
    return  cell;
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    //头cell
    UIView *headView = [UIView new];
    
    UIView *line =[[UIView alloc]initWithFrame:CGRectMake(0, (50-1)/2, DeviceWidth, 0.5)];
    line.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [headView addSubview:line];
    
    UIImageView *headImg = [[UIImageView alloc]initWithFrame:CGRectMake((DeviceWidth-80)/2, 5, 80, 40)];
    headImg.image = self.jrtj.count == 0 ? [UIImage imageNamed:@"home_past"]:section == 0 ? [UIImage imageNamed:@"home_update"]:[UIImage imageNamed:@"home_past"];
    [headImg setContentMode:UIViewContentModeScaleAspectFit];
    [headView addSubview:headImg];
    headView.backgroundColor =[UIColor whiteColor];
    headImg.backgroundColor =[UIColor whiteColor];


    
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 42;//每个cell的头部间距
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
{
    if ( self.jrtj.count != 0) {
        return 10;//每个cell的底部间距
    }else{
        return CGFLOAT_MIN;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ArticleViewController *articleViewController = [[ArticleViewController alloc]init];
    articleViewController.article = self.articles[indexPath.section][indexPath.row];
    articleViewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:articleViewController animated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_slimeView) {
        [_slimeView scrollViewDidScroll];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (_slimeView) {
        [_slimeView scrollViewDidEndDraging];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.articles objectAtIndex:section] count];
}

//section个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.articles count];
}

//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return EqualHeight(260, 608, DeviceWidth-20)+16;
}

//-(void)xsimge
//{
//    if ([Utils onePerform:@"xsimge2"]) {
//        UIView *xsview = [[UIView alloc]initWithFrame:[UIApplication sharedApplication].delegate.window.frame];
//        xsview.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
//        [[UIApplication sharedApplication].delegate.window addSubview:xsview];
//        
//        UIImageView *xsimge = [[UIImageView alloc]initWithFrame:CGRectMake(DeviceWidth-325, 0, 325, 176)];
//        xsimge.image = [UIImage imageNamed:@"home_tip_love-call_img"];
//        [xsimge setContentMode:UIViewContentModeScaleAspectFit];
//        [xsview addSubview:xsimge];
//        [xsview addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(xsview:)]];
//    }
//}

- (void)xsview:(UITapGestureRecognizer*)top
{
    [top.view removeFromSuperview];
}

@end
